package org.geektimes.projects.user.repository;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.orm.jpa.DelegatingEntityManager;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author :   chuan
 * @date :   2021/03/01
 */
public class HomeworkUserRepository implements UserRepository {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Resource(name = "bean/EntityManager")
    private DelegatingEntityManager delegatingEntityManager;

    @Resource(name = "bean/DelegatingValidator")
    private Validator validator;

    @Override
    public boolean save(User user) {
        try {
            Set<ConstraintViolation<User>> validate = validator.validate(user);
            if (validate.isEmpty()){
                if (user.getId() == null){
                    delegatingEntityManager.persist(user);
                }
                else {
                    delegatingEntityManager.merge(user);
                }
            }
            else {
                Map<String, Object> message = new LinkedHashMap<>();
                for (ConstraintViolation<User> violation : validate) {
                    message.put(violation.getMessageTemplate(), violation.getMessage());
                    logger.log(Level.INFO, violation.getMessage());
                }
                throw new RuntimeException(message.toString());
            }
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public boolean deleteById(Long userId) {
        return false;
    }

    @Override
    public boolean update(User user) {
        return false;
    }

    @Override
    public User getById(Long userId) {
        return null;
    }

    @Override
    public User getByNameAndPassword(String userName, String password) {
        return null;
    }

    @Override
    public Collection<User> getAll() {
        return null;
    }
}
